package net.zhengxinyun.performance.App.appCtrl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.sirdc.modules.utils.ObjectUtils;
import net.zhengxinyun.performance.App.dto.IndexDTOs.TownIndexAndScoreDTO;
import net.zhengxinyun.performance.App.dto.IndexDTOs.TownScoreDTO;
import net.zhengxinyun.performance.App.dto.IndexDTOs.TownWeightDTO;
import net.zhengxinyun.performance.App.dto.IndexUserDTO;
import net.zhengxinyun.performance.App.dto.ScoreDTO;
import net.zhengxinyun.performance.App.service.townIndex.TownIndexService;
import net.zhengxinyun.performance.Util.DataUtil;
import net.zhengxinyun.performance.Util.DateUtils;
import net.zhengxinyun.performance.Util.StringUtils;
import net.zhengxinyun.performance.core.Result;
import net.zhengxinyun.performance.core.ResultUtils;
import net.zhengxinyun.performance.data.UserAppDTO;
import net.zhengxinyun.performance.entity.TownEntity;
import net.zhengxinyun.performance.entity.TownIndicatorsEntity;
import net.zhengxinyun.performance.entity.UserEntity;
import net.zhengxinyun.performance.filter.*;
import net.zhengxinyun.performance.service.department.DepartmentService;
import net.zhengxinyun.performance.service.indicators.TownIndicatorsService;
import net.zhengxinyun.performance.service.indicators.TownScoreService;
import net.zhengxinyun.performance.service.indicators.TownService;
import net.zhengxinyun.performance.service.report.IndexReportService;
import org.apache.poi.ss.formula.functions.NumericFunction;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 县对乡镇 指标管理 指标考核得分
 */
@RestController
@RequestMapping("/app/townIndex")
public class TownIndexCtrl extends BaseCtrl {

    @Autowired
    private TownIndexService townIndexService;
    @Autowired
    private TownScoreService townScoreService;
    @Autowired
    private TownIndicatorsService webTownIndexService;
    @Autowired
    private TownService weightService;
    @Autowired
    private DepartmentService departmentService;
    @Autowired
    private IndexReportService reportService;


    //绩效App 市对县指标管理首页
    @PostMapping("/getTownIndex")
    public Result<HashMap<String, Object>> cityIndexHome(@RequestBody TownIndicatorsFilter filter) {
        HashMap<String, Object> dataMap = new HashMap<>();
       /* filter.setIndexType("二级指标");
        List<CountryIndicatorsFilter> listIndexs = cityIndexService.getAllCityIndex(filter);

        dataMap.put("data",listIndexs);*/
        if (StringUtils.isBlank(filter.getDateTime())) {
            filter.setDateTime(DateUtils.getCurrentYear());
        }
        filter.setIndexType("二级指标");
        List<TownIndicatorsFilter> allCityIndex = townIndexService.getAllTownIndex(filter); //查看指标
        dataMap.put("data", allCityIndex);
        System.out.println("-------接口： /getTownIndex");
        return ResultUtils.getResults(Result.Status.SUCCESS, "获取县对乡镇指标数据成功", dataMap);
    }

    // 乡镇指标 单个指标详情
    @PostMapping("/townIndexInfo")
    public Result<HashMap<String, Object>> singleIdexInfo(@RequestBody TownIndicatorsFilter filter) {
        if (StringUtils.isBlank(filter.getIndexId())) {
            return ResultUtils.getResults(Result.Status.ERROR, "indexId为空", null);
        }
        //List<TownEntity> townEntities = townIndexService.SingleIndexInfo(filter.getIndexId(), filter.getDepartCode(), null);
        HashMap<String, Object> map = new HashMap<>();

        String currentYear = getCurrentYear();

        //历史数据
        List<ScoreDTO> scoreDTOS = townIndexService.queryYearIndexInfo(filter.getIndexId(), filter.getDepartCode(), currentYear);
        String dateTime = filter.getDateTime();

        List<ScoreDTO> collect = scoreDTOS.stream().filter(o -> o.getDatetime().equals(dateTime)).collect(Collectors.toList());

        HashMap indexdata = new HashMap();
        if (ObjectUtils.isNotBlank(collect)) {
            indexdata.put("finalScore", collect.get(0).getFinalScore() + "");
            indexdata.put("rank", collect.get(0).getRank() + "");
        } else {
            indexdata.put("finalScore", 0);
            indexdata.put("rank", "-");
        }
        map.put("data", indexdata);
        map.put("historydata", scoreDTOS);

        System.out.println("-------接口： /townIndexInfo");
        return ResultUtils.getSuccessResults(map);
    }


    @PostMapping("/indexScore")
    public Result<HashMap<String, Object>> indexScore(@RequestBody IndexUserDTO dtofilter) {
        TownIndicatorsFilter townFilter = new TownIndicatorsFilter();
        BeanUtils.copyProperties(dtofilter, townFilter);
        //  UserFilter userFilter = new UserFilter();
        //userFilter.setUserPhone(dtofilter.getUserPhone());
        String tel = dtofilter.getUserPhone();
        UserFilter userInfo = getUserInfo(tel);

        List<ScoreDTO> indexScore = townIndexService.getIndexScore(townFilter, userInfo);
        HashMap<String, Object> dataMap = new HashMap<>();
        dataMap.put("data", indexScore);
        System.out.println("-------接口： /indexScore");
        return ResultUtils.getResults(Result.Status.SUCCESS, "县对乡镇考核数据返回成功", dataMap);

    }

    // 县对乡镇考核数据二级页面 单个乡镇下所有指标
    @PostMapping("/townScoreSecond")
    public Result<HashMap<String, Object>> townReport(@RequestBody IndexUserDTO dtofilter) {
        String currentYear = getCurrentYear();
        if (StringUtils.isBlank(dtofilter.getDepartcode())) {
            return ResultUtils.getResults(Result.Status.ERROR, "指标id(departcode)为空", null);
        }
        if (StringUtils.isBlank(dtofilter.getDateTime())) {
            dtofilter.setDateTime(DateUtils.getLastMonth(currentYear));
        }
        HashMap<String, Object> map = new HashMap<>();
        TownIndicatorsFilter filter = new TownIndicatorsFilter();
        filter.setDateTime(dtofilter.getDateTime());
        filter.setIndexYear(dtofilter.getDateTime().substring(0, 4));
        filter.setDepartCode(dtofilter.getDepartcode());
        List<TownIndicatorsFilter> townScoreList = townScoreService.getIndictScore(filter);
        List<ScoreDTO> scoreDTOS = new ArrayList<>();
        for (TownIndicatorsFilter item : townScoreList) {
            int rank = item.getRankInt();
            double finalScore = StringUtils.isBlank(item.getFinalScore()) ? 0 : Double.parseDouble(item.getFinalScore());
            double score = StringUtils.isBlank(item.getScore()) ? 0 : Double.parseDouble(item.getScore());
            int weight = StringUtils.isBlank(item.getWeight()) ? 0 : Integer.parseInt(item.getWeight());

            scoreDTOS.add(new ScoreDTO(Long.parseLong(item.getIndexId()), finalScore, score, weight, rank, null, dtofilter.getDepartcode(), item.getDateTime(), null, item.getIndexName()));
        }
        map.put("data", scoreDTOS);
        System.out.println("-------接口： /townScoreSecond");
        return ResultUtils.getSuccessResults(map);
    }


    // 指标分析
    @PostMapping("/townIndexRank")
    public Result<HashMap<String, Object>> townIndexRank(@RequestBody IndexUserDTO dtofilter) {
        TownIndicatorsFilter townFilter = new TownIndicatorsFilter();
        BeanUtils.copyProperties(dtofilter, townFilter);
        String currentYear = getCurrentYear();
        if (ObjectUtils.isBlank(dtofilter.getIndexId())) {
            return ResultUtils.getResults(Result.Status.ERROR, "指标id为空", null);
        }
        if (StringUtils.isBlank(townFilter.getDateTime())) {
            townFilter.setDateTime(DateUtils.getLastMonth(currentYear));
        }
        townFilter.setIndexId(dtofilter.getIndexId() + "");
        List<TownIndicatorsFilter> exporScore = townScoreService.getExporScore(townFilter);

        HashMap<String, Object> dataMap = new HashMap<>();
        dataMap.put("data", exporScore);
        System.out.println("-------接口： /townIndexRank");
        return ResultUtils.getResults(Result.Status.SUCCESS, "各乡镇指标排名得分", dataMap);

    }

    //app 获取指标管理中 乡镇指标
    @PostMapping("/townIndexManage")
    public Result<HashMap<String, Object>> getTownIndexs(@RequestBody TownIndexAndScoreDTO dto) {

        String userPhone = dto.getUserPhone();
        String currentYear = getCurrentYear();
        TownIndicatorsFilter townIndicatorsFilter = new TownIndicatorsFilter();
        townIndicatorsFilter.setDateTime(currentYear);
        townIndicatorsFilter.setIndexType("二级指标");
        townIndicatorsFilter.setAvail(1);
        List<TownIndicatorsFilter> query = webTownIndexService.query(townIndicatorsFilter);
        HashMap<String, Object> datamap = new HashMap<>();
        for (TownIndicatorsFilter indexItem : query) {
            Long id = indexItem.getId();
            TownFilter townFilter = new TownFilter();
            townFilter.setIndexId(id + "");
            List<TownFilter> townweight = weightService.queryByIndexId(id + "");
            List<TownWeightDTO> twds = new ArrayList<>();
            for (TownFilter weiItem : townweight) {
                twds.add(new TownWeightDTO(weiItem.getId(), weiItem.getTownName(), weiItem.getDepartcode(), DataUtil.integerParse(weiItem.getWeight())));
            }
            indexItem.setTownWeights(twds);
        }
        datamap.put("data", query);
        datamap.put("dateTime", currentYear);
        System.out.println("/townIndexManage");
        return ResultUtils.getSuccessResults(datamap);
    }

    //添加按钮操作：
    @PostMapping("/beforeAdd")
    public Result<HashMap<String, Object>> beforeAdd(@RequestBody UserAppDTO dto) {

        HashMap<String, Object> dataMap = new HashMap<>();
        DepartmentFilter departmentFilter = new DepartmentFilter();
     //   List<DepartmentFilter> alldept = departmentService.query(departmentFilter);
        departmentFilter.setDepartType("乡镇");
        List<DepartmentFilter> towns = departmentService.query(departmentFilter);
        List<TownWeightDTO> dtos =new ArrayList<>();
        for (DepartmentFilter town : towns) {
            TownWeightDTO tas = new TownWeightDTO();
            tas.setDepartcode(town.getDepartcode());
            tas.setTownName(town.getDepartAddr());
            dtos.add(tas);
        }
       // dataMap.put("allDepts", alldept);
        dataMap.put("townDepts", dtos);

        System.out.println("/beforeAdd");
        return ResultUtils.getSuccessResults(dataMap);
    }
    //app 乡镇指标增删改
    @PostMapping("/editTownIndex")
    public Result<String> editTownIndex(@RequestBody TownIndexAndScoreDTO dto) {
        String optionType = dto.getOptionType();
        String currentYear = getCurrentYear();
        if (StringUtils.isBlank(optionType)) {
            return ResultUtils.getResults(Result.Status.ERROR, "optionType 不能为空");
        }
        TownIndicatorsEntity townIndicatorsEntity = new TownIndicatorsEntity();
        townIndicatorsEntity.setIndexName(dto.getIndexName());
        townIndicatorsEntity.setLeadUnitName(dto.getLeadUnitName());
        townIndicatorsEntity.setAvail(1);
        townIndicatorsEntity.setDateTime(dto.getDateTime());
        townIndicatorsEntity.setIndexType("二级指标");
        townIndicatorsEntity.setResponsibilityUnit(dto.getResponsibilityUnit());
        townIndicatorsEntity.setSort(1);
        townIndicatorsEntity.setLeadUnit(dto.getDepartCode());
        String strtowns = dto.getTownWeights();
        List<TownEntity>  townWeights  = new ArrayList<>();
        JSONArray array = JSONArray.parseArray(strtowns);




        switch (optionType) {
            case "add":


                if (StringUtils.isBlank(strtowns)) {
                    return ResultUtils.getResults(Result.Status.ERROR, "townWeights数组 不能为空");
                }

                for (int i = 0; i < array.size(); i++) {

                    JSONObject jsonObject = array.getJSONObject(i);
                    TownEntity town  = jsonObject.toJavaObject(TownEntity.class);

                    townWeights.add(town);

                }
                townIndicatorsEntity.setId(null);
                String insert = webTownIndexService.insert(townIndicatorsEntity, townWeights);
                break;
            case "update":
                if (StringUtils.isBlank(strtowns) || ObjectUtils.isBlank(dto.getId())) {
                    return ResultUtils.getResults(Result.Status.ERROR, "townWeights数组 或者 id 不能为空");
                }
                for (int i = 0; i < array.size(); i++) {

                    JSONObject jsonObject = array.getJSONObject(i);
                    TownEntity town  = jsonObject.toJavaObject(TownEntity.class);

                    townWeights.add(town);

                }
                townIndicatorsEntity.setId(dto.getId());
                webTownIndexService.update(townIndicatorsEntity, townWeights);
                //webTownIndexService.update()
                break;
            case "del":
                Long id = dto.getId();
                if (ObjectUtils.isBlank(id)) {
                    return ResultUtils.getResults(Result.Status.ERROR, " id 不能为空");
                }
                townIndicatorsEntity.setId(id);
                webTownIndexService.delete(townIndicatorsEntity);
                break;
        }
        System.out.println("/editTownIndex");
        return ResultUtils.getSuccessResults();
    }

    //app 指标分数管理 获取所有分数指标
    @PostMapping("/townScoreManage")
    public Result<HashMap<String, Object>> getScoreindex(@RequestBody TownIndexAndScoreDTO param) {

        String userPhone = param.getUserPhone();
        UserFilter userInfo = getUserInfo(userPhone);


        DepartmentFilter departmentFilter = new DepartmentFilter();
        departmentFilter.setDepartType("乡镇");
        List<DepartmentFilter> towns = departmentService.query(departmentFilter);

        String currentYear = getCurrentYear();

        String datatime  = StringUtils.isBlank(param.getDateTime())? DateUtils.getLastMonth(currentYear):param.getDateTime();

        TownIndicatorsFilter townIndicatorsFilter = new TownIndicatorsFilter();
        townIndicatorsFilter.setDateTime(currentYear);
        townIndicatorsFilter.setIndexType("二级指标");
        townIndicatorsFilter.setAvail(1);
        List<TownIndicatorsFilter> query = webTownIndexService.query(townIndicatorsFilter);

        query =filterTownIndex(query,userInfo);

        //获取指标分数：
        for (TownIndicatorsFilter indexItem : query) {

            TownIndicatorsFilter filter = new TownIndicatorsFilter();
            filter.setDateTime(datatime);
            filter.setIndexId(indexItem.getId() + "");
            List<TownScoreDTO> scorelists = new ArrayList<>();
            List<TownIndicatorsFilter> exporScore = townScoreService.getExporScore(filter);
            for (TownIndicatorsFilter scoreItem : exporScore) {
                TownScoreDTO dto = new TownScoreDTO();
                dto.setDateTime(scoreItem.getDateTime());
                dto.setFinalScore(scoreItem.getDoubleFinaScore());
                dto.setId(scoreItem.getId());
                dto.setIndexId(indexItem.getId());
                dto.setRank(scoreItem.getRankInt());
                dto.setScore(DataUtil.doubleParse(scoreItem.getScore()));
                dto.setTownId(scoreItem.getDepartCode());
                dto.setTownName(scoreItem.getTownName());
                scorelists.add(dto);
                indexItem.setAudit(1 + "");
            }
            if (ObjectUtils.isBlank(exporScore)) {
                for (DepartmentFilter town : towns) {
                    TownScoreDTO dto = new TownScoreDTO();
                    dto.setDateTime(DateUtils.getLastMonth(currentYear));
                    dto.setFinalScore(0);
                    dto.setId(null);
                    dto.setIndexId(indexItem.getId());
                    dto.setRank(0);
                    dto.setScore(0);
                    dto.setTownId(town.getDepartcode());
                    dto.setTownName(town.getDepartAddr());
                    scorelists.add(dto);
                }


            }
            indexItem.setTownScores(scorelists);

        }

        HashMap<String, Object> dataMap = new HashMap<>();
        dataMap.put("data", query);
        dataMap.put("datetime", datatime);
        System.out.println("/townScoreManage");
        return ResultUtils.getSuccessResults(dataMap);
    }

    //编辑分数
    @PostMapping("/editTownScore")
    public Result<String> editTownScore(@RequestBody TownIndexAndScoreDTO param) {

        String optionType = param.getOptionType();
        String strTowns = param.getTownWeights();
        if (StringUtils.isBlank(strTowns) || ObjectUtils.isBlank(param.getId())) {
            return ResultUtils.getResults(Result.Status.ERROR, "townWeights, 指标id,不能为空");
        }

       List<TownEntity>  townWeights  = new ArrayList<>();
        JSONArray array = JSONArray.parseArray(strTowns);
        for (int i = 0; i < array.size(); i++) {

            JSONObject jsonObject = array.getJSONObject(i);
            TownEntity dto  = jsonObject.toJavaObject(TownEntity.class);

            townWeights.add(dto);

        }




        for (TownEntity town : townWeights) {
            if (com.sirdc.modules.utils.StringUtils.isBlank(town.getScore()) || "-".equals(town.getScore())) {
                if (com.sirdc.modules.utils.StringUtils.isNotBlank(town.getScore()))
                    town.setScore(town.getScore().replace("-", ""));
                continue;
            }
            Double score;
            try {
                score = Double.parseDouble(town.getScore());
            } catch (NumberFormatException e) {
                //town.getTownName()+town.getScore();
                return ResultUtils.getResults(Result.Status.ERROR, "数据格式，请输入纯数字或者小数,不包含其他字符。错误数据为：" + town.getTownName() + ":" + town.getScore() + " ;请重新输入");
            }


            town.setSocreRate(score.doubleValue());

        }

        Collections.sort(townWeights, new Comparator<TownEntity>() {
            @Override
            public int compare(TownEntity o1, TownEntity o2) {
                return -Double.compare(o1.getSocreRate(), o2.getSocreRate());
            }
        });

        String userPhone = param.getUserPhone();
        UserFilter userInfo = getUserInfo(userPhone);
        UserEntity userEntity = new UserEntity();
        BeanUtils.copyProperties(userInfo, userEntity);

        if (StringUtils.isBlank(param.getDateTime())) {
            param.setDateTime(DateUtils.getLastMonth(getCurrentYear()));
        }

        townScoreService.importScore(townWeights, param.getId(), userEntity, param.getDateTime());
        reportService.saveReport(userEntity, 2, param.getId(), param.getDateTime());

        System.out.println("/editTownScore");
        return ResultUtils.getSuccessResults("操作成功");
    }


}
